import { createRouter, createWebHashHistory } from 'vue-router'
import { getToken } from '@/utils/auth'
import { getAppTitle } from '@/utils/env'
import { useUserStore } from '@/store/user'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 标记是否已经获取过用户信息
let hasUserInfoFetched = false

// 路由配置
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/layout/index.vue'),
    redirect: '/drama/list',
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('@/views/home/index.vue'),
        meta: { title: '首页', requiresAuth: true }
      },
      {
        path: 'drama/list',
        name: 'DramaList',
        component: () => import('@/views/drama/list.vue'),
        meta: { title: '剧本列表', requiresAuth: true }
      },
      {
        path: 'drama/create',
        name: 'DramaCreate',
        component: () => import('@/views/drama/components/DramaDetail.vue'),
        meta: { title: '创建剧本', requiresAuth: true }
      },
      {
        path: 'drama/edit/:id',
        name: 'DramaEdit',
        component: () => import('@/views/drama/components/DramaDetail.vue'),
        meta: { title: '编辑剧本', requiresAuth: true }
      },
      {
        path: 'drama/detail/:id',
        name: 'DramaDetail',
        component: () => import('@/views/drama/components/DramaDetail.vue'),
        meta: { title: '剧本详情', requiresAuth: true }
      },
      {
        path: 'drama/storyboard/:dramaId/:seriesId',
        name: 'StoryboardDetail',
        component: () => import('@/views/drama/components/StoryboardDetail.vue'),
        meta: { title: '分镜详情', requiresAuth: true }
      },
      {
        path: 'drama/role/:dramaId',
        name: 'RoleManagement',
        component: () => import('@/views/drama/components/RoleManagement.vue'),
        meta: { title: '角色管理', requiresAuth: true }
      },
      {
        path: 'drama/scene/:dramaId',
        name: 'SceneManagement',
        component: () => import('@/views/drama/components/SceneManagement.vue'),
        meta: { title: '场景管理', requiresAuth: true }
      },
      {
        path: 'video-player-demo',
        name: 'VideoPlayerDemo',
        component: () => import('@/views/drama/components/VideoPlayerDemo.vue'),
        meta: { title: '视频播放器示例', requiresAuth: true }
      },
      {
        path: 'image-editor-demo',
        name: 'ImageEditorDemo',
        component: () => import('@/views/drama/components/ImageEditorExample.vue'),
        meta: { title: '图片编辑器示例', requiresAuth: true }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/'
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 配置NProgress
NProgress.configure({ showSpinner: false })

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 开始进度条
  NProgress.start()
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - ${getAppTitle()}` : getAppTitle()
  
  // 判断是否需要登录权限
  if (to.meta.requiresAuth !== false) {
    const token = getToken()
    
    if (token) {
      // 已登录，只在首次访问或刷新时获取用户信息
      const userStore = useUserStore()
      
      // 只在以下情况获取用户信息：
      // 1. 首次访问（hasUserInfoFetched为false）
      // 2. userStore中没有用户信息（页面刷新后store会被重置）
      if (!hasUserInfoFetched || !userStore.userInfo.userId) {
        try {
          // 从token中解析userId或从其他方式获取
          // 这里假设userId可以从token或其他地方获取
          // 你可能需要根据实际情况调整获取userId的方式
          const userId = getUserIdFromToken(token) // 这个函数需要你实现
          if (userId) {
            await userStore.getUserInfoById(userId)
            hasUserInfoFetched = true // 标记已获取过用户信息
          }
        } catch (error) {
          console.error('获取用户信息失败:', error)
          // 获取用户信息失败时可以考虑是否跳转到登录页
        }
      }
      
      next()
    } else {
      // 未登录则跳转到登录页
      next({ path: '/login', query: { redirect: to.fullPath } })
    }
  } else {
    // 不需要登录权限的页面
    if (to.path === '/login' && getToken()) {
      // 已登录状态下访问登录页，重定向到首页
      next({ path: '/' })
    } else {
      next()
    }
  }
})

// 从token中解析userId的辅助函数
function getUserIdFromToken(token) {
  try {
    // 如果token是JWT格式，可以解析payload获取userId
    // 这里需要根据你的token格式来实现
    const payload = JSON.parse(atob(token.split('.')[1]))
    return payload.userId || payload.sub || payload.id
  } catch (error) {
    console.error('解析token失败:', error)
    // 如果解析失败，可能需要从其他地方获取userId
    // 或者调用一个专门的接口来获取当前用户信息
    return null
  }
}

// 路由后置守卫
router.afterEach(() => {
  // 结束进度条
  NProgress.done()
})

export default router 